package sit.engreal.leetcode.problems400;

import org.junit.jupiter.api.Assertions;

/**
 * <a href="https://leetcode.cn/problems/valid-perfect-square/">367. 有效的完全平方数</a>
 */
public class LeetCode367 {
    public boolean isPerfectSquare(int num) {
        if (num < 1) {
            return false;
        }
        int left = 1;
        int right = num;
        while (left < right) {
            final int mid = (right - left) / 2 + left;
            final int v = mid * mid;
            if (v / mid != mid) {
                right = mid - 1;
            } else if (v > num) {
                right = mid - 1;
            } else if (v < num) {
                left = mid + 1;
            } else {
                return true;
            }
        }

        return left * right == num;
    }

    public static void main(String[] args) {
        final LeetCode367 demo = new LeetCode367();

        Assertions.assertFalse(demo.isPerfectSquare(Integer.MAX_VALUE));
        Assertions.assertFalse(demo.isPerfectSquare(46340));

        Assertions.assertTrue(demo.isPerfectSquare(1));
        Assertions.assertTrue(demo.isPerfectSquare(4));
        Assertions.assertTrue(demo.isPerfectSquare(46340 * 46340));
    }
}
